package com.bky.service.impl;

import com.bky.queue.Consumer;
import com.bky.queue.Produce;
import com.bky.util.ExecutorThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.*;

/**
 * Created by shipeilei on 2017/5/25.
 */
@Component
public class TimeTaskService {
    private static final Logger LOGGER = LoggerFactory.getLogger("TimeTaskService");
    @Autowired
    private QueryService queryService;
    private Produce produce = null;
    private Consumer consumer = null;
    private BlockingQueue<Map> queue = new ArrayBlockingQueue<>(1024);

    @PostConstruct
    public void start() {
        try {
            MDC.put("invokeNo", UUID.randomUUID().toString());
            LOGGER.info("定时任务开始");

            if (null == produce) {
                produce = new Produce(queue, queryService, LOGGER);
            }
            if (null == consumer) {
                consumer = new Consumer(queue, queryService, LOGGER);
            }
            ExecutorThreadFactory factory = new ExecutorThreadFactory("scheduledPool");
            ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(2, factory);
            scheduledPool.scheduleAtFixedRate(produce, 0, 10, TimeUnit.SECONDS);
            scheduledPool.scheduleAtFixedRate(consumer, 0, 10, TimeUnit.SECONDS);
        } catch (Exception e) {
            LOGGER.error("定时任务异常", e);
        }finally {
            MDC.remove("invokeNo");
        }
    }
}
